<?php
namespace control;
//访客计划
class visitPlanClass extends adIndexClass
{
    private const page = 'visitPlan'; # 权限
    private const table = 'visit_plan'; # 数据表
    private const title = '访客计划';
    public array $weekArray = array("日", "一", "二", "三", "四", "五", "六");

    /*入口页*/
    public function home()
    {
        $checkedColor = '';
        if (empty($this->get('stid')) || $this->get('stid')==self::$stid){
            $checkedColor = "see-now";
        }
        $see[] = self::$stid;
        $li="<li class='$checkedColor' data-id='".self::$stid."'>".L('visitPlan.home.me')."</li>";
        $result = find(array('table'=>'staff','where'=>"manager = '".self::$stid."'"));
        foreach ($result['array'] as $array){
            $checkedColor = '';
            if ($array['stid'] == $this->get('stid')){
                $checkedColor = "see-now";
            }
            $li.="<li class='$checkedColor' data-id='".$array['stid']."'>{$array['name']}</li>";
            $see[] = $array['stid'];
        }


        $mark = [];
        if (empty($this->get('stid'))){
            $where = " and stid = '".self::$stid."'";
        }else{
            $where = " and stid = '{$this->get('stid')}' and stid in ('".implode("','",$see)."')";
        }
        $where.=" and coid = '".self::$coid."'";
        $page = find([
            'table' => self::table,
            'where' => $where
        ]);
        foreach ((array)$page['array'] as $item) {
            $mark[$item['locationDate']] = '';
        }
        $mark = json_encode($mark, 320);

        $date = $this->get('date');
        $leftHtml = <<<EOT
        <div id="work-report-box"></div>
        <script>
        function replaceRightDetail(date, type=null){
            let api = root + 'control/adIndex.html?cla={$this->get('cla')}&fun=homeRight'
            let stid = GetQueryString('stid');
            $.post(api, { date: date, stid: stid}, function (data) {
                $('#container-detail').html(data.html)
            }, "json");
        }

        laydate.render({
            elem: '#work-report-box',
            theme: 'default',
            mark: {$mark},
            value: '{$date}',
            ready: function(date){
                let now = date.year+'-'+date.month+'-'+date.date;
                return replaceRightDetail(now);
            }
            ,done: function(value, date){
                console.log(value);
                let now = date.year+'-'+date.month+'-'+date.date;
                $("[name='hideDate']").val(value)
                return replaceRightDetail(now);
            }
            ,showBottom: false
            ,position: 'static'
            });
        </script>
EOT;
        $html = <<<EOT
        <div class="container-main">
            <div class="container-left left" id="container-left">
                <input name="hideDate" type="hidden" value="{$date}">
                 <div style="min-height: 50px"><ul class="followQuick staffUl">{$li}</ul></div>
                {$leftHtml}
            </div>
            <div class="container-right left" id="container-detail">
            </div>
        </div>
<script>
 $(".followQuick li").on('click',function() {
    let id = $(this).data('id');
    let date = $("[name='hideDate']").val();
    location.href = root+'control/adIndex.html?cla=visitPlan&fun=home&stid='+id+'&date='+date;

 })
     /**
* 根据客户返回地址
*/
function getKehuAddress(){
    let khid = $("[name='khid']").val();
    let address = $("[name='address']").val();
    $.post(root+'control/adIndex.html?cla=visitPlan&fun=getAddress',{khid:khid,address:address},function(res) {
        $("[name='address']").val(res.address);
    },'json')
}
</script>
<style>
 .staffUl li{
   height: 25px;
   width: 40px;
   text-align: center;
   line-height: 23px;
 }
 .see-now{
   background-color: rgb(158, 208, 255) !important;
 }
 .container-main .container-left {width: 275px;}
 .container-main .container-left li{width: auto;min-width: 35px;justify-content: center;}
</style>
EOT;
        //返回
        return $this->homeFun($html);
    }


    public function homeRight()
    {
        $date = $this->post('date') ?? '';
        return $this->detail($date,$this->post('stid'));
    }

    /**
     * 编辑页面
     * @return string
     */
    public function editPage(): string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $option = ['15分钟前'=>L('visitPlan.editPage.15MinutesAgo'), '无'=>L('visitPlan.editPage.nothing'), '日程开始时'=>L('visitPlan.editPage.beginning'), '1小时前'=>L('visitPlan.editPage.hourAgo'), '1天前'=>L('visitPlan.editPage.dayAgo')];
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('visitPlan.editPage.theme') => text(['name' => "theme", 'value' => $info['theme']]),
                    L('visitPlan.editPage.client') =>clientClass::kehuSelect(array('value'=>$info['khid'],'change'=>"getKehuAddress()")),
                ],
                [
                    must .L('visitPlan.editPage.chooseTime') => text(['name' => "chooseTime", 'laydate'=>['type'=>'datetime','range'=>'~'],'value' => strtotime($info['startTime'])>0?($info['startTime'].' ~ '.$info['endTime']):'']),
                ],
                [
                    L('visitPlan.editPage.remindTime') => radio(array('name' => 'remindTime', 'value' => $option, 'checked' => $info['remindTime']?:'无')),
                ],
                [
                    L('visitPlan.editPage.member') => selectMultiple(array('table' => 'staff', 'multiple' => true, "title" => L('visitPlan.editPage.choice'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'member[]', 'value' => $info['member'])),
                    L('visitPlan.editPage.address') =>text(["name" => "address", 'title'=>L('visitPlan.editPage.keyword'), "value" => $info['address']]) .(componentClass::addressIco("layer('".self::page."','map',{})")),
                ],
                [
                    L('visitPlan.editPage.text') => textarea(['name' => "text", 'class' => 'textarea', 'value' => $info['text']]),
                ],
            ],'hidden'=>hidden(array('name'=>'date','value'=>$this->post('date'))),
        ]
        );
        $html.= <<<efo
<script>
$(function(){
    $("input[name='address']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=component&fun=getAddress',
        callback:function(data){

        }
    });

})

</script>
efo;

        //返回
        return $this->layer(array("title" => L('visitPlan.editPage.edit'), "height" => 400, "width" => 800, "html" => $html));
    }

    /**
     * 根据客户ID查找地址
     * @return bool|string
     */
    public function getAddress(): bool|string
    {
        $kehu = query('kehu',"khid = '".$this->post('khid')."'");
        if ($this->post('address')){
            $json['address'] = $this->post('address');
        }else{
            $json['address'] = $kehu['address'];
        }
        return json_encode($json,320);
    }

    /**
     * 地图选址
     */
    public function map(){
        $key = para('tencentMapKey');
        $sureWord = L('visitPlan.map.sure');
        $addressSelectionWord = L('visitPlan.map.addressSelection');
        $html =<<<efo
<iframe id="mapPage" width="100%" height="90%" frameborder=0
    src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={$key}&referer=myapp">
</iframe>
<div style="text-align: center;padding: 10px"><input onclick="$('#visitPlanMap').hide()" class="button" type="button" value="{$sureWord}"></div>
<script>
    window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            //移除监听
           event.stopPropagation();
          // $("[name='location']").val(loc.latlng.lat+','+loc.latlng.lng);
          $("[name='address']").val(loc.poiaddress);
        }
    }, false);
</script>
efo;

        return $this->layer(array("title" => $addressSelectionWord, "height" => 800, "width" => 1000, "html" => $html));
    }
    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $timeArr = explode(' ~ ',$this->post('chooseTime'));
        $field = [
            'theme' => $this->post('theme'),
            'khid' => $this->post('khid'),
            'startTime' => $timeArr[0],
            'endTime' => $timeArr[1],
            'remindTime'=>$this->post('remindTime'),
            'member'=>$this->post('member') ? implode(',',$this->post('member')) :'',
            'address'=>$this->post('address'),
            'text'=>$this->post('text'),
        ];
        $annotation = [
            'theme' => L('visitPlan.editPageEdit.theme'),
            'startTime' => L('visitPlan.editPageEdit.startTime'),
            'endTime' => L('visitPlan.editPageEdit.endTime'),
        ];
        $rules = [
            'theme' => 'required',
            'startTime' => 'required',
            'endTime'      => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('visitPlan.editPageEdit.power');
        }elseif(empty($this->post('date'))){
            $json['warn'] = L('visitPlan.editPageEdit.dateEmpty');
        }elseif(!$this->checkRemindTime($field['remindTime'],$field['startTime'])){
            $json['warn'] = L('visitPlan.editPageEdit.remindTimeError');
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            $field['startRemindTime'] = $this->startRemindTime($field['remindTime'],$field['startTime']);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid'=>self::$coid,
                    'locationDate'=>$this->post('date'),
                    'stid' => self::$stid,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('visitPlan.editPageEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&date=" . $this->post('date');
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 添加消息
     */
    public function startRemindTime($type,$startTime){
        switch ($type){
            case '15分钟前':
                $time = date('Y-m-d H:i:s',strtotime($startTime)-15*60);
                break;
            case '日程开始时':
                $time = $startTime;
                break;
            case '1小时前':
                $time = date('Y-m-d H:i:s',strtotime($startTime)-60*60);
                break;
            case '1天前':
                $time = date('Y-m-d H:i:s',strtotime($startTime)-24*60*60);
                break;
            default:
                $time = '';
                break;
        }
        return $time;
    }

    /**
     * 检查提前提醒时间和计划开始时间是否有冲突
     */
    public function checkRemindTime($type,$startTime): bool
    {
        switch ($type){
            case '15分钟前':
                $bool = time()<strtotime($startTime)-15*60;
                break;
            case '日程开始时':
                $bool = time()<strtotime($startTime);
                break;
            case '1小时前':
                $bool = time()<strtotime($startTime)-60*60;
                break;
            case '1天前':
                $bool = time()<strtotime($startTime)-60*60*24;
                break;
            default:
                $bool = true;
                break;
        }
        return $bool;
    }


    /**
     * 成果编辑
     */
    public function result(){
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $html = $this->layerEdit([
                "table" => [
                    [
                        must .L('visitPlan.result.factTime') => text(['name' => "factTime", 'class' => 'long', 'laydate'=>['type'=>'datetime','range'=>'~'],'value' => strtotime($info['factStartTime'])>0?($info['factStartTime'].' ~ '.$info['factEndTime']):'']),
                    ],
                    [
                        L('visitPlan.result.achievement') => textarea(['name' => "achievement", 'class' => 'textarea', 'value' => $info['achievement']]),
                    ],
                    [
                        L('visitPlan.result.signImg') => fileUploadClass::addFileComponent($id,'访客计划',self::page,'visitPlanResultForm'),
                    ],
                ],
            ]
        );
        //返回
        return $this->layer(array("title" => L('visitPlan.result.edit'), "height" => 400, "width" => 800, "html" => $html));
    }

    /**
     * 成果编辑
     */
    public function resultEdit(){
        // 文件id
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id');
        $timeArr = explode(' ~ ',$this->post('factTime'));
        $field = [
            'factStartTime' => $timeArr[0],
            'factEndTime' => $timeArr[1],
            'achievement'=>$this->post('achievement'),
        ];
        $annotation = [
            'achievement' => L('visitPlan.resultEdit.achievement'),
            'factStartTime' => L('visitPlan.resultEdit.factStartTime'),
            'factEndTime' => L('visitPlan.resultEdit.factEndTime'),
        ];
        $rules = [
            'achievement' => 'required',
            'factStartTime' => 'required',
            'factEndTime'      => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, "id = '$id'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('visitPlan.resultEdit.power');
        }elseif(empty($info['id'])){
            $json['warn'] = L('visitPlan.resultEdit.empty');
        }elseif(strtotime($field['factEndTime']) <=strtotime($field['factStartTime'])){
            $json['warn'] = L('visitPlan.resultEdit.endTimeError');
        }elseif(strtotime($field['factEndTime']) >time()){
            $json['warn'] = L('visitPlan.resultEdit.factEndTimeError');
        } else {
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => " id = '$id'"
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (is_array($fileIdArr)) {
                    update([
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ]);
                }
                //清除待办
                backlogEnd(array(
                    "stid" => self::$stid,
                    "typeId" => $id,
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('visitPlan.resultEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }


    public function detail($date,$stid)
    {
        //like查询数组
        $like = [];
        //全等查询数组
        $equal = array(
            "locationDate" => $date,//对象
            "stid" => $stid?:self::$stid,//跟进员工
        );

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, "where" => $where,'pageNum'=>20, "order" => "startTime desc"));
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','editPage',{id:'" . self::getId() . "',date:'".$date."'})\" class='spanButton'>".L('visitPlan.detail.newSchedule')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('visitPlan.detail.del')."</span>\n";
        }
        $time = date('m月d日 周' . $this->weekArray[date('w', strtotime($date))], strtotime($date));
        if (strtotime($date) ==strtotime($this->date)){
            $time.=L('visitPlan.detail.today');
        }
        $button .= "<span class='title-color'>{$time}</span>";
        //返回
        $json['html'] = "<div class='flex-box p-10'>{$button}</div>" . $page['hint'] . "<form name='listForm'>"  . $this->tableOther($page['array']) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 列表
     */
    public function tableOther($data): string
    {
        $html = '';
        foreach ($data as $array) {
            $time = date('H:i', strtotime($array['startTime']));
            $kehu = query('kehu', "khid = '$array[khid]'");
            $staffName = clueClass::showMember($array['member'], 2);
            $name = self::findStaff($array['stid']);
            $factTime = strtotime($array['factStartTime'])>0?($array['factStartTime'].'至'.$array['factEndTime']):'--';
            $root = root;

            $img='';
            $fileResult = find(array('table'=>'file','where'=>"targetId = '$array[id]' order by time"));
            foreach ($fileResult['array'] as $file){
                //列表控件
                $dominate = array(
                    "img" => array("title" => $file['name'], "href" => $file['src']),
                );
                $img.=$this->dominate($dominate);
            }
            $delWord = L('visitPlan.tableOther.del');
            $resultsWord = L('visitPlan.tableOther.results');
            $editWord = L('visitPlan.tableOther.edit');
            $companyNameWord = L('visitPlan.tableOther.companyName');
            $addressWord = L('visitPlan.tableOther.address');
            $textWord = L('visitPlan.tableOther.text');
            $timeWord = L('visitPlan.tableOther.time');
            $toWord = L('visitPlan.tableOther.to');
            $factTimeWord = L('visitPlan.tableOther.factTime');
            $achievementWord = L('visitPlan.tableOther.achievement');
            $signImgWord = L('visitPlan.tableOther.signImg');
            $signAddressWord = L('visitPlan.tableOther.signAddress');
            $personnelWord = L('visitPlan.tableOther.personnel');
            $stidWord = L('visitPlan.tableOther.stid');
            $createTimeWord = L('visitPlan.tableOther.createTime');
            $html .= <<<efo
    <div style="background-color: #F2F2F2;width: 100%;margin: 10px;padding: 10px;box-sizing: border-box;">
        <div class="list-title"><input name="listId" type="checkbox" value="{$array['id']}">&emsp;<span style="font-weight: bold">{$time}|{$array['theme']}</span>
            <img alt="{$delWord}" title="{$delWord}" onclick="layer('{$this->get('cla')}','operate',{act:'del',id:'{$array['id']}'})" src="{$root}img/control/delete.svg">
            <img alt="{$resultsWord}" title="{$resultsWord}" onclick="layer('{$this->get('cla')}','result',{id:'{$array['id']}'})"   src="{$root}img/control/result.svg">
            <img alt="{$editWord}" title="{$editWord}" onclick="layer('{$this->get('cla')}','editPage',{id:'{$array['id']}',date:'{$array['locationDate']}'})"  src="{$root}img/control/edit.svg">
        </div>
    <div>
         <ul class="visitUl">
             <li>{$companyNameWord}：{$kehu['companyName']}&emsp;{$addressWord}：{$array['address']}&emsp;{$textWord}：{$array['text']}&emsp;</li>
             <li>{$timeWord}：{$array['startTime']}{$toWord}{$array['endTime']}&emsp;{$array['remindTime']}&emsp;</li>
             <li>{$factTimeWord}：{$factTime}&emsp;{$achievementWord}：{$array['achievement']}&emsp;{$signImgWord}：{$img}&emsp;{$signAddressWord}：{$array['signAddress']}</li>
             <li>{$personnelWord}：{$staffName}&emsp;<span style="float: right">{$stidWord}：{$name}&emsp;{$createTimeWord}：{$array['time']}</span></li>
        </ul>
    </div>
    </div>
<style>
.visitUl>li{
   margin: 10px;
}
.list-title img{
  cursor: pointer;float: right;margin-right: 10px;width: 22px;
}
</style>
efo;

        }
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('visitPlan.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('visitPlan.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('visitPlan.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('visitPlan.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['stid'] != self::$stid) {
                    //返回
                    $warn = L('visitPlan.delete.fail');
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除待办
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('visitPlan.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('visitPlan.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('visitPlan.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('visitPlan.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
